from django.contrib.auth.decorators import login_required
from kalapankki.payment.models import Payment
from django.core.urlresolvers import reverse
from kalapankki.payment.helpers import create_payment_key, get_payment_from_request
from django.http import HttpResponseNotAllowed, Http404
from kalapankki.utils import get_pages, render_with_request_context
from kalapankki.album.models import Album

SELLER_ID = 'kalapankkisid123'
SECRET_KEY = '00f8272257320cbd6addd2007844af22'

@login_required
def order(request, album_id, page_number=1):
    if request.method == "POST":
        amount = request.POST.get("amount",1)
        payment = Payment(user = request.user, album_id = album_id, amount = amount)
        payment.save()
        album=Album.objects.get(owner=request.user, id=album_id)
        checksum = create_payment_key(payment,SELLER_ID, SECRET_KEY)
        success_url = request.build_absolute_uri(reverse("payment_success", kwargs={"user_id":request.user.id, "page_number":page_number}))
        cancel_url = request.build_absolute_uri(reverse("payment_cancel", kwargs={"user_id":request.user.id, "page_number":page_number}))
        error_url = request.build_absolute_uri(reverse("payment_error", kwargs={"user_id":request.user.id, "page_number":page_number}))
        return render_with_request_context(request, 'payment_form.html', {"payment":payment,
                     "checksum":checksum, "user":request.user,"seller_id":SELLER_ID,
                     "error_url":error_url, "success_url":success_url, "cancel_url":cancel_url, "album_name":album.name })
    return HttpResponseNotAllowed

def failure(request, resp_type, user_id, page_number=1):
    payment = get_payment_from_request(request,user_id,SECRET_KEY)
    if payment:
        pages = get_pages(request,payment.album.page_set, page_number)
        payment.delete()
        rcontext = {"payment":payment, "pages":pages, "album":payment.album}
        if resp_type == 'error':
            rcontext["error"] = True
            return render_with_request_context(request,"payment_finished.html",rcontext)
        else:
            rcontext["canceled"] = True
            return render_with_request_context(request,"payment_finished.html",rcontext)
    else:
        raise Http404

def success(request, user_id, page_number=1):
    payment = get_payment_from_request(request,user_id,SECRET_KEY)
    if payment:
        pages = get_pages(request,payment.album.page_set, page_number)
        payment.ref = request.GET.get("ref")
        payment.state = 'F'
        payment.save()
        return render_with_request_context(request,"payment_finished.html", {"finished":True, "payment":payment,"pages":pages, "album":payment.album})
    else:
        raise Http404